package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.domain.Type;
import com.ml4ai.backend.dto.TypeDTO;
import com.ml4ai.backend.repository.TypeRepository;
import com.ml4ai.backend.utils.Bean2Bean;
import com.ml4ai.backend.utils.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by uesr on 2018/9/12.
 */
@Component
public class TypeMapper extends BaseMapper<Type, TypeDTO> {

    @Autowired
    TypeRepository typeRepository;

    @Override
    public Type newEntity() {
        return new Type();
    }

    @Override
    public TypeDTO newDTO() {
        return new TypeDTO();
    }

    @Override
    public Type find(Long id) {
        return typeRepository.getOne(id);
    }

    @Override
    public void entity2dto(Type entity, TypeDTO dto) {
        new Bean2Bean().addPropMapper(
                new PropertyMapper<>("parent", "parent", this::e2d),
                new PropertyMapper<>("parent.id", "parentId")
        ).copyProperties(entity, dto);
    }

    @Override
    public void dto2entity(TypeDTO dto, Type entity) {
        new Bean2Bean().addExcludeProp("parent").copyProperties(dto, entity);
        Long parentId = Bean2Bean.getFirstNoNullVal(dto, "parentId", "parent.id");
        if (parentId != null)
            entity.setParent(typeRepository.getOne(parentId));
        else
            entity.setParent(null);
    }
}
